package com.bjpowernode.boss.exceptions;

import com.bjpowernode.boss.web.model.response.Result;
import com.bjpowernode.enums.RespCode;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.validation.BindException;
import org.springframework.validation.FieldError;
import org.springframework.web.bind.annotation.ExceptionHandler;
import org.springframework.web.bind.annotation.RestControllerAdvice;

import java.util.List;


@RestControllerAdvice
public class GlobalExceptionHandle {
private Logger logger = LoggerFactory.getLogger(GlobalExceptionHandle.class);
    @ExceptionHandler({BossException.class})
    public Result doBossException(BossException e){
        logger.error("[doBossException]Boss异常:{}:{}"
                +e.getRespCode().getCode()+
                e.getRespCode().getMsg());
        return Result.fail(e.getRespCode());
    }

//处理beanvalidation的异常
    @ExceptionHandler({BindException.class})
    public Result doBeanvalidation(BindException bind){
        StringBuilder builder = new StringBuilder();
        List<FieldError> fieldErrors = bind.getFieldErrors();//获取不满足@validated注解约束的属性
        for (FieldError fe : fieldErrors) {
            builder.append("错误项：【").append(fe.getField()).append("】;")
                    .append("错误原因：【").append(fe.getDefaultMessage()).append("】")
                    .append("丨");
        }
        Result result = new Result();
         result.setCode(RespCode.LOGIN_PARAM_ERROR.getCode());
         result.setMsg(builder.toString());
         result.setData("");
         return result;

    }

}
